﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeChatParking.Core.Payment.UnionPay
{
    public class ActiveAct
    {
        #region 车辆状态  通过
        /// <summary>
        /// 此接口由智慧通行平台行提供，运营商可以通过调用此接口查询车辆绑定以及无感支付签约状态。URL Test OK  通过
        /// </summary>
        /// <param name="plateNumber">车牌</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string carStatusQuery(string plateNumber, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            queryCar model = new queryCar();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.plateNumber = plateNumber;
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                          Newtonsoft.Json.Formatting.None,
                          new JsonSerializerSettings
                          {
                              NullValueHandling = NullValueHandling.Ignore
                          });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model);
            string url = String.Format("/car/sign/status?appId={0}&plateNumber={1}&timestamp={2}&signature={3}", model.appId, model.plateNumber, model.timestamp, model.signature);
            return doRequest_Get(url);
        }
        #endregion
        #region 支付 通过
        /// <summary>
        /// 车辆驶出停车场后，运营商可以通过此接口推送订单到智慧通行平台 URL Test OK
        /// </summary>
        /// <param name="syncId">支付请求唯一序列号，由运营商生成</param>
        /// <param name="orderId">订单号，由运营商生成</param>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="payAmount">发送给智慧通行平台的订单金额，精确到分，以分为单位。用户支付到运营商实际金额（比如运营商扣除优惠劵，代金券等）</param>
        /// <param name="serviceAmount">总金额，精确到分，以分为单位。用户在运营商产生的总费用</param>
        /// <param name="startTime">车辆进入停车场时间。UTC时间。例如：2018-03-16T16:06:05Z</param>
        /// <param name="endTime">车辆离开停车场时间。UTC时间。例如：2018-03-16T16:06:05Z</param>
        /// <param name="parkId">运营商分配给停车场的id，由运营商定义</param>
        /// <param name="parkName">运营商分配给停车场的名称，由运营商定义</param>
        /// <param name="accSplitData">分账域</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string payBill(string syncId, string orderId, string plateNumber, int payAmount, int serviceAmount, DateTime startTime, DateTime endTime, string parkId, string parkName, string accSplitData, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            requersOrderInfo model = new requersOrderInfo();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.industryCode = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayIndustryCode;
            model.data = new orderInfo()
            {
                syncId = syncId,
                plateNumber = plateNumber,
                orderId = orderId,
                payAmount = payAmount,
                serviceAmount = serviceAmount,
                orderDate = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                startTime = startTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                endTime = endTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                parkId = parkId,
                parkName = parkName,
                payCallback = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayCallback,
                accSplitData = accSplitData
            };
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                     Newtonsoft.Json.Formatting.None,
                     new JsonSerializerSettings
                     {
                         NullValueHandling = NullValueHandling.Ignore
                     });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model,
                     Newtonsoft.Json.Formatting.None,
                     new JsonSerializerSettings
                     {
                         NullValueHandling = NullValueHandling.Ignore
                     });
            return doRequest_Post(request, "/pay/bill");
        }
        /// <summary>
        /// 此接口由智慧通行平台提供，运营商可以通过调用此接口查询订单状态 URL Test OK
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string payStatus(string orderId, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            queryOrder model = new queryOrder();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.orderId = orderId;
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                    Newtonsoft.Json.Formatting.None,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model);
            string url = String.Format("/pay/status?appId={0}&orderId={1}&timestamp={2}&signature={3}", model.appId, model.orderId, model.timestamp, model.signature);
            return doRequest_Get(url);

        }
        #endregion
        #region 退款  通过
        /// <summary>
        /// 此接口由智慧通行平台提供，运营商可以通过调用此接口查询退款订单状态 URL Test OK
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string refundStatus(string orderId, string upRefundId, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            UnionPay.refundStatus model = new UnionPay.refundStatus();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.orderId = orderId; 
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            model.upRefundId = upRefundId;
            var json = JsonConvert.SerializeObject(model,
                   Newtonsoft.Json.Formatting.None,
                   new JsonSerializerSettings
                   {
                       NullValueHandling = NullValueHandling.Ignore
                   });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model);
            string url = String.Format("/refund/status?appId={0}&orderId={1}&upRefundId={2}&timestamp={3}&signature={4}", model.appId, model.orderId, model.upRefundId, model.timestamp, model.signature);
            return doRequest_Get(url);
        }
        /// <summary>
        /// 此接口由智慧通行平台提供，接收运营商的退款请求。URL Test OK
        /// </summary>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="refundAmount">实际退款金额，精确到分，以分为单位。如果存在优惠活动必须以订单金额全额退款</param>
        /// <param name="refundId">退款流水号，由运营商生成</param>
        /// <param name="orderId">已经支付成功的订单号，由运营商生成</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string refundBill(string plateNumber, int refundAmount, string refundId, string orderId, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            refundBill model = new refundBill();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.data = new Refund()
            {
                plateNumber = plateNumber,
                refundAmount = refundAmount,
                refundId = refundId,
                orderId = orderId,
                refundCallback = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayRefundCallback,
            };
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                    Newtonsoft.Json.Formatting.None,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
            model.signature = UnionPayCommon.signParam(json, key);
            request = JsonConvert.SerializeObject(model);
            return doRequest_Post(request, "/refund/bill");
        }
        #endregion
        #region 进出场通知  通过
        /// <summary>
        /// 此接口由智慧通行平台提供，运营商向智慧通行平台推送车辆入场通知  URL Test OK  通过
        /// </summary>
        /// <param name="syncId">停车记录唯一标识</param>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="startTime">进场时间</param>
        /// <param name="parkId">运营商分配给停车场的id，由运营商定义</param>
        /// <param name="parkName">运营商分配给停车场的名称，由运营商定义</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string noticeEntrance(string syncId, string plateNumber, DateTime startTime, string parkId, string parkName, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            requestInfo model = new requestInfo();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.data = new EntryInfo()
            {
                syncId = syncId,
                plateNumber = plateNumber,
                startTime = startTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                parkId = parkId,
                parkName = parkName
            };
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                        Newtonsoft.Json.Formatting.None,
                        new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model);
            return doRequest_Post(request, "/notice/entrance");
        }
        /// <summary>
        /// 此接口由智慧通行平台提供，运营商向智慧通行平台推送车辆出场通知 URL Test OK
        /// </summary>
        /// <param name="syncId">停车记录唯一标识</param>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="startTime">进场时间</param>
        /// <param name="endTime">出场时间</param>
        /// <param name="parkId">运营商分配给停车场的id，由运营商定义</param>
        /// <param name="parkName">运营商分配给停车场的名称，由运营商定义</param>
        /// <param name="request"></param>
        /// <returns></returns>
        public string noticeExit(string syncId, string plateNumber, DateTime startTime, string parkId, string parkName, out string request)
        {
            string key = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey;
            requestInfo model = new requestInfo();
            model.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
            model.data = new ExitInfo()
            {
                syncId = syncId,
                plateNumber = plateNumber,
                startTime = startTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                endTime = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ"),
                parkId = parkId,
                parkName = parkName
            };
            model.timestamp = int.Parse(WeChatParking.Util.Comm.GetTimeStamp().ToString());
            var json = JsonConvert.SerializeObject(model,
                       Newtonsoft.Json.Formatting.None,
                       new JsonSerializerSettings
                       {
                           NullValueHandling = NullValueHandling.Ignore
                       });
            string signature = UnionPayCommon.signParam(json, key);
            model.signature = signature;
            request = JsonConvert.SerializeObject(model);
            return doRequest_Post(request, "/notice/exit");
        }
        #endregion
        private string doRequest_Get(string url)
        {
            url = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayUrl + url;
            return WeChatParking.Util.HttpUtil.DoGet(url);
        }
        private string doRequest_Post(string paramData, string url)
        {
            url = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayUrl + url;
            return WeChatParking.Util.HttpUtil.PostUrl(url, paramData);
        }
    }
}
